<?php

class SelectComponent extends BlueprintComponent {
	
	function parse(&$element, $value, $source = null, $display = null, $key = null) {
		$doc = $element->document;
		
		if ($discardOptions) {
			while($element->hasChildNodes()) {
				$element->removeChild($element->lastChild);
			}
		} else {
			
			// add the selected="selected" code to existing options
			for($i = 0; $i < count($element->childNodes); $i++) {
				$node = $element->childNodes[$i];
				if ($node->nodeName == "option") {
					if (isset($node->attribute['value']))
						$node->code = "<?= ($value == \"{$node->attribute['value']}\") ? ' selected=\"selected\"' : '' ?>";
					else
						$node->code = "<?= ($value == \"{$node->childNodes[0]->data}\") ? ' selected=\"selected\"' : '' ?>";
				}
			}
		}
		
		if (!$source) {
			return; // we're finished
		}
		
		$element->appendChild($doc->createPHPNode("foreach ($source as \$key => \$value) {"));
		
		$option = $doc->createElement("option");
		$key = $key ? "->$key" : '';
		$display = $display ? "->$display" : '';
		if ($key) {
			$option->attributes["value"] = "<?= \$value$key ?>";
			$option->code = "<?= ($value == \$value$key) ? ' selected=\"selected\"' : '' ?>";
		} else {
			$option->code = "<?= ($value == \$value$display) ? ' selected=\"selected\"' : '' ?>";
		}
		$option->appendChild($doc->createPHPTextNode("\$value$display"));
		$element->appendChild($option);
		$element->appendChild($doc->createPHPNode('}'));
	}
}
?>